package cn.com.oceansoft.osc.ms.utils;

import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;

import java.io.ByteArrayOutputStream;
import java.security.*;


import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author wuzy
 * @created 2017-04-13-17:03
 * @email wzy@oceansoft.com.cn
 */
public class PoliceMoneyUtil {


    /**
     * our_publicKey:MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpnAJdZNFneNPil+mfeg5uWT/8YoCb/1IiUkFmt25hMfTBix0N5qC9vfU62Kt/ii30Qc9zX7CB2NpwYwDKQ2OaSr7RKQ73CmwH1ww5uY+JYIBOJ8ys8N1txG8fR0eHFLrYBA2M5UWLYQVUsXS8jeGU0VqrU9MpcVyKIqzpA6veKQIDAQAB
     * our_privateKey:MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKmcAl1k0Wd40+KX6Z96Dm5ZP/xigJv/UiJSQWa3bmEx9MGLHQ3moL299TrYq3+KLfRBz3NfsIHY2nBjAMpDY5pKvtEpDvcKbAfXDDm5j4lggE4nzKzw3W3Ebx9HR4cUutgEDYzlRYthBVSxdLyN4ZTRWqtT0ylxXIoirOkDq94pAgMBAAECgYAp5k53P/azNxgw/BJMwVxbSlUSRks7PmHN9MAPXfU4sZyjS3iL/JNtDEZOmUQUp9AebTuQZu01xpp/9RU24lryVcom/2oeT6oxvq79e2VFoDqRL5ly8LAAk9674vZx60jpUy+3e6Ltl7nvsNZwPPcLW4MgoVZX5160UqOQu6L/WQJBANhQloGPCyYgQCdwhr3agMzh1Ya4iIdUQM37Vx0KFOcD8XeBeooxo9sdG3yfia9vP3k5lnBWIM+9BlcGHwP7ha8CQQDIudzEo8m1jAzdzMcXHRfsIgGv3m90dodhCZ9XtfPwIOVosz5rOznMsKsjFuW29YGsRjTahfa8hqGYnIVi5ienAkEAldilmhRUPdIDfw61WFk/9i3PM+crNMwJpGcjPouYVTvnDskT8R1YC9aLDvaZc30WNEzPSPxw+FdSSACGhcS8IwJBALgplv0vjSStbyyc8lkpj0ZOWR/jxHylN0Z3zqNpxHsfo3uxYOZ/e2NrAEl8e5ymmafW7i1EVgHYwDDGAreflOcCQHrl3VK0Lw5LYK3rFkdjc/gfkdaZXAbsDFVejYpIl2niqRjXM3fx3KCvfVeJu3oB/RdvUy4X17/8uYFym+vfTpc=
     * @param
     * @param
     * @return
     */


    public static String encyptPublicKey (String reqData) throws Exception {

        byte[] data =reqData.getBytes();
        String publicKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCZnIFoD6j7chrEhLK8x1QzCZLe8RTPDKWKhgUmlvSuq6xcVn2pHPoYoI3CL2dtHyi0ixmf1xU2FCmBPNZRC1DoEYW/DdJcZlRFTqO5T+71bvJEqKKRiRzvSgNKqHGptswF+lHAjibWOAphcFWCa43EWqbfvbHrojV4qD5Htuo66wIDAQAB";
        byte[] keyBytes = Base64.decodeBase64(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key publicK = keyFactory.generatePublic(x509KeySpec);


        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicK);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > 117) {
                cache = cipher.doFinal(data, offSet, 117);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * 117;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return  (new BASE64Encoder()).encode(encryptedData).replaceAll("\r\n", "");

    }

    public static String isOk(String repData,String signStr) {
        try {
            byte[] sign = Base64.decodeBase64(Base64.decodeBase64(signStr));
            String oriRepData=new String(Base64.decodeBase64(repData),"UTF-8");
            String siteCode="";
            String transacCode="";
            //String data=siteCode+transacCode+oriRepData;
            String data=oriRepData;
            String publicKeystr="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCZnIFoD6j7chrEhLK8x1QzCZLe8RTPDKWKhgUmlvSuq6xcVn2pHPoYoI3CL2dtHyi0ixmf1xU2FCmBPNZRC1DoEYW/DdJcZlRFTqO5T+71bvJEqKKRiRzvSgNKqHGptswF+lHAjibWOAphcFWCa43EWqbfvbHrojV4qD5Htuo66wIDAQAB";
            byte[]publicKey=Base64.decodeBase64(publicKeystr);//对提供的公钥做 base64 解
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey pubKey = keyFactory.generatePublic(keySpec) ;
            Signature signature = Signature.getInstance("MD5withRSA");
            signature.initVerify(pubKey);
            signature.update(data.getBytes("UTF-8"));
            boolean ok= signature.verify(sign);
            if(ok){
                return "1";
            }else{
                return "0";
            }
        }
        catch ( Exception e) {
            e.printStackTrace();
            return "0";
        }
    }

    public static String encyptRsa(String respData,String siteCode,String transacCode)
    {
        try {
            String prikeyStr="MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKmcAl1k0Wd40+KX6Z96Dm5ZP/xigJv/UiJSQWa3bmEx9MGLHQ3moL299TrYq3+KLfRBz3NfsIHY2nBjAMpDY5pKvtEpDvcKbAfXDDm5j4lggE4nzKzw3W3Ebx9HR4cUutgEDYzlRYthBVSxdLyN4ZTRWqtT0ylxXIoirOkDq94pAgMBAAECgYAp5k53P/azNxgw/BJMwVxbSlUSRks7PmHN9MAPXfU4sZyjS3iL/JNtDEZOmUQUp9AebTuQZu01xpp/9RU24lryVcom/2oeT6oxvq79e2VFoDqRL5ly8LAAk9674vZx60jpUy+3e6Ltl7nvsNZwPPcLW4MgoVZX5160UqOQu6L/WQJBANhQloGPCyYgQCdwhr3agMzh1Ya4iIdUQM37Vx0KFOcD8XeBeooxo9sdG3yfia9vP3k5lnBWIM+9BlcGHwP7ha8CQQDIudzEo8m1jAzdzMcXHRfsIgGv3m90dodhCZ9XtfPwIOVosz5rOznMsKsjFuW29YGsRjTahfa8hqGYnIVi5ienAkEAldilmhRUPdIDfw61WFk/9i3PM+crNMwJpGcjPouYVTvnDskT8R1YC9aLDvaZc30WNEzPSPxw+FdSSACGhcS8IwJBALgplv0vjSStbyyc8lkpj0ZOWR/jxHylN0Z3zqNpxHsfo3uxYOZ/e2NrAEl8e5ymmafW7i1EVgHYwDDGAreflOcCQHrl3VK0Lw5LYK3rFkdjc/gfkdaZXAbsDFVejYpIl2niqRjXM3fx3KCvfVeJu3oB/RdvUy4X17/8uYFym+vfTpc=";

            String oriRepData=new String(Base64.decodeBase64(respData),"UTF-8");
            String data= siteCode+transacCode+oriRepData;
            byte[] keyBytes = Base64.decodeBase64(prikeyStr.getBytes());//对私钥做 base64 解码

            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);

            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec) ;

            Signature signature = Signature.getInstance("MD5withRSA");

            signature.initSign(priKey);

            signature.update(data.getBytes("UTF-8"));//data 为要生成签名的源数据字节数组

            String result= Base64.encodeBase64String(Base64.encodeBase64String(signature.sign()).getBytes());
            return  result;
        } catch ( Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
}
